<template>
  <div class="chat-history-container">
    <!-- 空状态提示 -->
    <div class="empty-tip" v-if="chatList.length === 0 && !isAiResponding">
      <el-empty
          image-size="120"
          description="暂无对话记录，请输入「为[用户名]推荐...」格式查询"
      >
        <template #extra>
          <el-button type="text" size="small" @click="handleGuide">查看示例</el-button>
        </template>
      </el-empty>
    </div>

    <!-- 对话列表 -->
    <div class="chat-list" ref="chatListRef">
      <div
          class="chat-item"
          v-for="(item, index) in chatList"
          :key="index"
          :class="item.role === 'user' ? 'user-chat' : 'ai-chat'"
      >
        <!-- 角色头像 -->
        <div class="chat-avatar">
          <el-avatar size="medium">
            <span>{{ item.role === 'user' ? '我' : '助' }}</span>
          </el-avatar>
        </div>

        <!-- 对话内容区 -->
        <div class="chat-content">
          <div class="chat-role">
            {{ item.role === 'user' ? '我' : '穿搭助手' }}
            <span class="chat-time">{{ item.timestamp }}</span>
          </div>

          <!-- 消息内容容器 -->
          <div class="chat-message-container">
            <div class="chat-message" v-html="formatMessage(item.content)"></div>
            <span class="typing-animation" v-if="item.isLoading">
              <span>.</span><span>.</span><span>.</span>
            </span>
          </div>

          <!-- 附加信息 -->
          <div class="chat-meta" v-if="item.role === 'ai' && item.meta">
            <span class="meta-item">Token消耗：{{ item.meta.prompt_tokens }}+{{ item.meta.completion_tokens }}</span>
          </div>
        </div>
      </div>

      <!-- AI加载中提示 -->
      <div class="loading-item" v-if="isAiResponding">
        <el-avatar size="medium">
          <span>助</span>
        </el-avatar>
        <div class="loading-content">
          <div class="loading-role">穿搭助手</div>
          <div class="loading-message">正在根据用户信息生成推荐...</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, onUnmounted } from 'vue'
import { ElAvatar, ElEmpty, ElMessage } from 'element-plus'
import eventBus from '../utils/eventBus'

// 响应式数据
const chatList = ref([])
const isAiResponding = ref(false)
const currentAiIndex = ref(-1)
const chatListRef = ref(null)

// 查看示例
const handleGuide = () => {
  ElMessage.info({
    title: '查询示例',
    message: `
      1. 为小明推荐夏季爬山穿搭<br>
      2. 为小红推荐通勤职场穿搭<br>
      3. 为李华推荐学生党休闲穿搭
    `,
    dangerouslyUseHTMLString: true,
    duration: 5000
  })
}

// 格式化消息
const formatMessage = (content) => {
  if (!content) return ''
  // 转义HTML特殊字符
  let formatted = content
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;')

  // 处理换行
  formatted = formatted.replace(/\n/g, '<br>')

  // 高亮穿搭关键词
  const outfitKeywords = /(上衣|裤子|裙子|鞋子|外套|内搭|配饰|风格|场合|材质|颜色|尺码)/g
  formatted = formatted.replace(outfitKeywords, '<span class="highlight">$1</span>')

  return formatted
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatListRef.value) {
    chatListRef.value.scrollTop = chatListRef.value.scrollHeight
  }
}

// 监听事件
onMounted(() => {
  // 新增用户消息
  eventBus.on('add-user-message', (userMsg) => {
    console.log('👤 收到用户消息事件:', userMsg)
    
    chatList.value.push({
      role: 'user',
      content: userMsg.content,
      timestamp: userMsg.timestamp,
      meta: null,
      isLoading: false
    })
    scrollToBottom()

    // 初始化AI消息
    isAiResponding.value = true
    currentAiIndex.value = chatList.value.length
    chatList.value.push({
      role: 'ai',
      content: '',
      timestamp: userMsg.timestamp,
      meta: null,
      isLoading: true
    })
    
    console.log('📝 当前聊天列表:', chatList.value)
  })

  // 新增AI流式片段
  eventBus.on('add-ai-message-chunk', (chunk) => {
    console.log('🤖 收到AI消息片段:', chunk, '当前索引:', currentAiIndex.value)
    
    if (currentAiIndex.value >= 0 && currentAiIndex.value < chatList.value.length) {
      chatList.value[currentAiIndex.value].content += chunk
      console.log('📝 更新AI消息内容:', chatList.value[currentAiIndex.value].content)
      scrollToBottom()
    } else {
      console.warn('⚠️ AI消息索引无效:', currentAiIndex.value, '聊天列表长度:', chatList.value.length)
    }
  })

  // AI响应完成
  eventBus.on('ai-response-complete', (meta) => {
    console.log('✅ AI响应完成事件:', meta)
    
    isAiResponding.value = false
    if (currentAiIndex.value >= 0 && currentAiIndex.value < chatList.value.length) {
      chatList.value[currentAiIndex.value].isLoading = false
      chatList.value[currentAiIndex.value].meta = meta
      console.log('📝 完成AI消息:', chatList.value[currentAiIndex.value])
    }
  })

  // AI响应错误
  eventBus.on('ai-response-error', (errorMsg) => {
    console.log('❌ AI响应错误事件:', errorMsg)
    
    isAiResponding.value = false
    if (currentAiIndex.value >= 0 && currentAiIndex.value < chatList.value.length) {
      chatList.value[currentAiIndex.value].content = `推荐失败：${errorMsg}`
      chatList.value[currentAiIndex.value].isLoading = false
    }
  })

  // 清空历史
  eventBus.on('clear-history', () => {
    console.log('🗑️ 清空历史事件')
    
    chatList.value = []
    isAiResponding.value = false
    currentAiIndex.value = -1
  })

  // 加载历史
  eventBus.on('load-history', (historyList) => {
    console.log('📚 加载历史事件:', historyList)
    
    chatList.value = historyList.map(item => ({
      ...item,
      isLoading: false,
      meta: item.meta || null
    }))
    scrollToBottom()
  })
})

// 监听对话列表变化
watch(chatList, () => {
  scrollToBottom()
  eventBus.emit('chat-list-updated')
}, { deep: true })

// 组件卸载
onUnmounted(() => {
  eventBus.off('add-user-message')
  eventBus.off('add-ai-message-chunk')
  eventBus.off('ai-response-complete')
  eventBus.off('ai-response-error')
  eventBus.off('clear-history')
  eventBus.off('load-history')
  eventBus.off('chat-list-updated')
})
</script>

<style scoped>
.chat-history-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 12px;
  margin-top: 16px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
}

.empty-tip {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.chat-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding-bottom: 10px;
}

.chat-item {
  display: flex;
  gap: 12px;
  padding: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: box-shadow 0.2s ease;
}

.chat-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.user-chat {
  flex-direction: row-reverse;
  align-self: flex-end;
  background-color: #f0f7ff;
}

.ai-chat {
  align-self: flex-start;
}

.chat-avatar {
  margin-top: 4px;
}

.chat-content {
  flex: 1;
  max-width: calc(100% - 60px);
}

.chat-role {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
}

.user-chat .chat-role {
  color: #165dff;
}

.ai-chat .chat-role {
  color: #36ad47;
}

.chat-time {
  font-size: 12px;
  font-weight: normal;
  opacity: 0.7;
}

.chat-message-container {
  position: relative;
  padding: 12px;
  border-radius: 8px;
}

.user-chat .chat-message-container {
  background-color: #e6f4ff;
  color: #0047cc;
}

.ai-chat .chat-message-container {
  background-color: #f9f9f9;
  color: #333;
}

.chat-message {
  line-height: 1.6;
  font-size: 15px;
  word-break: break-all;
}

.highlight {
  color: #ff7a45;
  font-weight: 500;
}

.typing-animation {
  display: inline-block;
  margin-left: 4px;
}

.typing-animation span {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #36ad47;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-animation span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-animation span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.loading-item {
  display: flex;
  gap: 12px;
  padding: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  align-self: flex-start;
}

.loading-avatar {
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.loading-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.loading-role {
  font-size: 14px;
  font-weight: 500;
  color: #36ad47;
  margin-bottom: 4px;
}

.loading-message {
  font-size: 15px;
  color: #666;
}

.chat-meta {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

.meta-item {
  margin-right: 16px;
}

@media (max-width: 768px) {
  .chat-history-container {
    padding: 12px;
    margin-top: 8px;
  }

  .chat-message {
    font-size: 14px;
  }

  .chat-content {
    max-width: calc(100% - 50px);
  }
}
</style>
